# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:20
@Auth： gubei
@File：serializers.py
@IDE：PyCharm
@Description：用户数据模型和序列化器
"""

from enum import Enum
from typing import List, Optional
from datetime import datetime

from pydantic import BaseModel, Field, EmailStr, validator


class UserRegisterSchema(BaseModel):
    """用户注册模型"""
    username: str = Field(..., min_length=3, max_length=20, description="用户名，长度3-20个字符")
    nickname: str = Field(..., min_length=2, max_length=50, description="用户昵称，长度2-50个字符")
    password: str = Field(..., min_length=6, description="用户密码，最小长度6个字符")
    role: int = Field(..., description="用户角色ID")
    mobile: Optional[str] = Field(None, regex=r"^1[3-9]\d{9}$", description="手机号，可选")
    email: Optional[EmailStr] = Field(None, description="电子邮箱，可选")
    
    @validator('username')
    def username_alphanumeric(cls, v):
        if not v.isalnum():
            raise ValueError('用户名必须是字母和数字的组合')
        return v


class UserUpdate(BaseModel):
    """用户更新模型"""
    id: int = Field(..., description="用户ID")
    nickname: str = Field(..., min_length=2, max_length=50, description="用户昵称")
    password: Optional[str] = Field("******", description="用户密码，如不修改请填写******")
    role: int = Field(..., description="用户角色ID")
    mobile: Optional[str] = Field(None, regex=r"^1[3-9]\d{9}$", description="手机号，可选")
    email: Optional[EmailStr] = Field(None, description="电子邮箱，可选")
    
    class Config:
        schema_extra = {
            "example": {
                "id": 1,
                "nickname": "测试用户",
                "password": "******",
                "role": 1,
                "mobile": "13800138000",
                "email": "test@example.com"
            }
        }


class UserPwdUpdate(BaseModel):
    """用户密码更新模型"""
    id: int = Field(..., description="用户ID")
    password: str = Field(..., min_length=6, description="新密码，最小长度6个字符")
    
    @validator('password')
    def password_not_placeholder(cls, v):
        if v == "******":
            raise ValueError('请输入新密码而不是占位符')
        return v


class UserRole(str, Enum):
    """用户角色枚举"""
    super_admin = "super_admin"
    admin = "admin"
    user = "user"


class UserBase(BaseModel):
    """用户基础模型"""
    username: str = Field(..., description="用户名")
    
    class Config:
        orm_mode = True


class User(UserBase):
    """用户模型（用于API输入）"""
    password: str = Field(..., min_length=6, description="密码")


class UserInDB(UserBase):
    """数据库中的用户模型（带哈希密码）"""
    hashed_password: str


class TokenData(BaseModel):
    """令牌数据模型"""
    username: Optional[str] = None
    scopes: List[str] = []


class UserToken(BaseModel):
    """用户令牌信息模型"""
    id: int
    user_name: str
    nick_name: str
    disabled: bool


class UserResponse(BaseModel):
    """用户响应模型（用于API输出）"""
    id: int
    userName: str
    nickName: str
    role: str
    isActive: int
    mobile: Optional[str] = None
    email: Optional[str] = None
    created_at: Optional[datetime] = None
    
    class Config:
        orm_mode = True
